﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SMS.Business.Stocks;
using SMS.DAL.Providers;
using SMS.Business;
using SMS.DAL;
using SMS.Business.Customer;
using SMS.Business.Items;

namespace SMS.Orders
{
    public partial class InsertSellingOrder : System.Web.UI.Page
    {
        DAL.User CurrentUser
        {
            get
            {
                return (DAL.User)Session["CurrentUser"];
            }
        }

        public List<OrderItem> OrderItemsSource
        {
            set
            {
                if ((List<OrderItem>)Session["OrderItemsList"] == null)
                    Session["OrderItemsList"] = new List<OrderItem>();
                else
                    Session["OrderItemsList"] = value;
            }
            get
            {
                if ((List<OrderItem>)Session["OrderItemsList"] == null)
                    return new List<OrderItem>();
                else
                    return (List<OrderItem>)Session["OrderItemsList"];
            }
        }

        decimal? Total
        {
            set
            {
                ViewState["Total"] = value;
            }
            get
            {
                return (decimal)ViewState["Total"];
            }
        }
        decimal discount;

        string QryStockItemID;

        ItemBusiness ItemBus;

        private void BindCustomersDDL()
        {
            CustomerBussiness customerBus = new CustomerBussiness();
            //ddlCustomers.Items.Insert(0, new ListItem("أخــر", "0"));
            List<Customer> customers = customerBus.GetAll();
            customers.Insert(0, new Customer() { ID = 0, Name = "None" });
            ddlCustomers.DataSource = customers;
            ddlCustomers.DataValueField = "ID";
            ddlCustomers.DataTextField = "Name";
            ddlCustomers.DataBind();
        }

        private void BindStocksDDL()
        {

            StocksBusiness stockBus = new StocksBusiness();
            StockUserSearchCriteria stockUserSearch = new StockUserSearchCriteria()
            {
                UserID = CurrentUser.ID
            };
            ddlStocks.DataSource = stockBus.GetByUserID(stockUserSearch);
            ddlStocks.DataValueField = "ID";
            ddlStocks.DataTextField = "Name";
            ddlStocks.DataBind();
        }

        private void BindDlOrderItems()
        {
            this.dlOrderItems.DataSource = OrderItemsSource;
            this.dlOrderItems.DataBind();

            decimal? totalPerItem = 0;
            OrderItem item = new OrderItem();
            for (int i = 0; i < OrderItemsSource.Count; i++)
            {
                item = OrderItemsSource[i];
                Label lblTotalPerItem = (Label)dlOrderItems.Items[i].FindControl("lblItemTotal");
                if (lblTotalPerItem != null)
                {
                    totalPerItem = item.ItemCount * item.UnitPrice;
                    lblTotalPerItem.Text = totalPerItem.ToString();
                }
            }
        }

        private Item GetItem(ItemSearchCriteria itemSearch)
        {
            ItemBus = new ItemBusiness();
            Item item = ItemBus.Search(itemSearch).FirstOrDefault();
            if (item == null)
            {
                string urlQuary = "ItemName=" + HttpUtility.UrlPathEncode(itemSearch.Name) +
                    "&ItemMark=" + HttpUtility.UrlPathEncode(itemSearch.Mark)
                    + "&Stock=" + HttpUtility.UrlPathEncode(ddlStocks.SelectedValue) +
                    "&Barcode=" + HttpUtility.UrlPathEncode(itemSearch.Barcode) + "&type=2";
                Response.Redirect("~/Items/NewItem.aspx?" + urlQuary);
            }
            return item;
        }

        private StockItem GetStockItem(StockItemsSearchCriteria StockItemSearch, Item item)
        {
            StockItemsBussiness stockItemBus = new StockItemsBussiness();
            StockItemSearch = new StockItemsSearchCriteria()
            {
                ItemID = item.ID,
                StockID = int.Parse(ddlStocks.SelectedValue)
            };
            StockItem stockItem = stockItemBus.GetByItemIDAndStockID(StockItemSearch);
            if (stockItem == null)
            {
                string urlQuary = "ItemID=" + HttpUtility.UrlPathEncode(item.ID.ToString()) + "&Stock="
                    + HttpUtility.UrlPathEncode(ddlStocks.SelectedValue) + "&type=2";
                Response.Redirect("~/Items/NewItem.aspx?" + urlQuary);
            }
            return stockItem;
        }

        private OrderItem CreateOrderItem(StockItem stockItem)
        {
            OrderItem orderItem = new OrderItem()
            {
                ItemCount = 1,
                UnitPrice = stockItem.Item.SellingPrice,
                StockItem = stockItem
            };
            return orderItem;
        }

        private List<OrderItem> AddingOrderItems(OrderItem orderItem)
        {
            for (int i = 0; i < OrderItemsSource.Count; i++)
            {
                if (OrderItemsSource[i].StockItemID == orderItem.StockItemID)
                {
                    OrderItemsSource[i].ItemCount++;
                    return OrderItemsSource;
                }
            }
            OrderItemsSource.Add(orderItem);
            return OrderItemsSource;
        }
        #region Events
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["CurrentUser"] == null)
                Response.Redirect(@"~\Account\Login.aspx");
            if (!IsPostBack)
            {
                QryStockItemID = Request.QueryString["StockItemID"];
                if (QryStockItemID != null)
                {
                    StockItemsBussiness stockItemBus = new StockItemsBussiness();
                    StockItem stockItem = stockItemBus.GetByID(int.Parse(QryStockItemID));
                    this.AddingOrderItems(CreateOrderItem(stockItem));
                }
                if (OrderItemsSource.Count > 0)
                    this.BindDlOrderItems();
                else
                    OrderItemsSource = new List<OrderItem>();
                this.BindCustomersDDL();
                this.BindStocksDDL();
            }
        }

        protected void txtBarCode_TextChanged(object sender, EventArgs e)
        {
            string strBarcode = txtBarCode.Text;
            txtBarCode.Text = string.Empty;
            ItemSearchCriteria itemSearch = new ItemSearchCriteria()
            {
                Barcode = strBarcode,
            };
            Item item = GetItem(itemSearch);
            StockItemsSearchCriteria stockItemSearch = new StockItemsSearchCriteria()
            {
                ItemID = item.ID
            };
            StockItem stockItem = GetStockItem(stockItemSearch, item);
            OrderItem orderItem = this.CreateOrderItem(stockItem);
            this.AddingOrderItems(orderItem);
            BindDlOrderItems();
        }

        protected void txtMark_TextChanged(object sender, EventArgs e)
        {
            ItemSearchCriteria itemSearch = new ItemSearchCriteria()
            {
                Name = txtItemName.Text,
                Mark = txtMark.Text
            };
            txtItemName.Text = string.Empty;
            txtMark.Text = string.Empty;
            Item item = GetItem(itemSearch);
            StockItemsSearchCriteria stockItemSearch = new StockItemsSearchCriteria()
            {
                ItemID = item.ID
            };
            StockItem stockItem = GetStockItem(stockItemSearch, item);
            OrderItem orderItem = this.CreateOrderItem(stockItem);
            this.AddingOrderItems(orderItem);
            this.BindDlOrderItems();
        }

        protected void ddlCustomers_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlCustomers.SelectedValue != "0")
            {
                lblDiscountPercentage.Visible = true;
                txtDiscountPercentage.Visible = true;
                CustomerBussiness custBus = new CustomerBussiness();
                Customer customer = custBus.GetByID(int.Parse(ddlCustomers.SelectedValue));
                txtDiscountPercentage.Text = customer.DiscountPercentage.ToString();
            }
        }

        protected void txtPaid_TextChanged(object sender, EventArgs e)
        {
            lblChange.Text = (Total - decimal.Parse(txtPaid.Text)).ToString();
        }

        protected void txtDiscountPercentage_TextChanged(object sender, EventArgs e)
        {
            this.BindDlOrderItems();
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (OrderItemsSource.Count > 0)
            {
                vldtrsOrderItems.IsValid = true;
                OrderBusiness orderBus = new OrderBusiness();

                StockUserSearchCriteria StockUserSearch = new StockUserSearchCriteria()
                {
                    StockID = int.Parse(ddlStocks.SelectedValue),
                    UserID = CurrentUser.ID
                };
                StockUser stockUser = orderBus.GetUserStockByUserIDandStockID(StockUserSearch);


                Order BuyingOrder = new Order()
                {
                    Date = DateTime.Now,
                    PaidPrice = decimal.Parse(txtPaid.Text),
                    StockUserID = stockUser.ID,
                    TotalPrice = Total,
                    Type = 2    // For Selling Orders
                };
                if (ddlCustomers.SelectedValue != "0")
                {
                    BuyingOrder.CustomerID = int.Parse(ddlCustomers.SelectedValue);
                    BuyingOrder.DiscountAmount = decimal.Parse(txtDiscountPercentage.Text);
                }
                int orderID = orderBus.InsertOrder(BuyingOrder);
                OrderItemsBussiness orderItemBus = new OrderItemsBussiness();
                foreach (var item in OrderItemsSource)
                {
                    item.OrderID = orderID;
                    orderItemBus.Insert(item);
                }
                // Order Printing
                OrderItemsSource = null;
                this.BindDlOrderItems();
            }
            else
                vldtrsOrderItems.IsValid = false;
        }

        #region datalist Event

        protected void dlOrderItems_CancelCommand(object source, DataListCommandEventArgs e)
        {
            this.dlOrderItems.EditItemIndex = -1;
            this.BindDlOrderItems();
        }

        protected void dlOrderItems_DeleteCommand(object source, DataListCommandEventArgs e)
        {
            OrderItemsSource.RemoveAt(e.Item.ItemIndex);
            this.BindDlOrderItems();
        }

        protected void dlOrderItems_EditCommand(object source, DataListCommandEventArgs e)
        {
            dlOrderItems.EditItemIndex = e.Item.ItemIndex;
            this.BindDlOrderItems();
        }

        protected void dlOrderItems_ItemCommand(object source, DataListCommandEventArgs e)
        {

        }

        protected void dlOrderItems_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Footer)
            {
                if (ddlCustomers.SelectedValue != "0")
                    discount = decimal.Parse(txtDiscountPercentage.Text);
                Label lblTotal = (Label)e.Item.FindControl("lblTotal");
                Total = 0;
                foreach (var item in OrderItemsSource)
                {
                    Total += (item.ItemCount * item.UnitPrice);
                }
                decimal? totalAfterDis = Total - (Total * (discount / 100));
                lblTotal.Text = totalAfterDis.ToString();
            }
        }

        protected void dlOrderItems_UpdateCommand(object source, DataListCommandEventArgs e)
        {
            TextBox txtQuantity = (TextBox)e.Item.FindControl("txtQuantity");
            TextBox txtUnitPrice = (TextBox)e.Item.FindControl("txtSellingPrice");
            int quantity = int.Parse(txtQuantity.Text);
            decimal unitPrice = decimal.Parse(txtUnitPrice.Text);
            OrderItemsSource[e.Item.ItemIndex].UnitPrice = unitPrice;
            OrderItemsSource[e.Item.ItemIndex].StockItem.Item.SellingPrice = unitPrice;
            OrderItemsSource[e.Item.ItemIndex].ItemCount = quantity;
            dlOrderItems.EditItemIndex = -1;
            BindDlOrderItems();
        }
        #endregion

        protected void txtPartNumber_TextChanged(object sender, EventArgs e)
        {
            string partNumber = txtPartNumber.Text;
            txtPartNumber.Text = string.Empty;
            ItemSearchCriteria itemSearch = new ItemSearchCriteria()
            {
                PartNumber = partNumber
            };
            Item item = GetItem(itemSearch);
            StockItemsSearchCriteria stockItemSearch = new StockItemsSearchCriteria()
            {
                ItemID = item.ID
            };
            StockItem stockItem = GetStockItem(stockItemSearch, item);
            OrderItem orderItem = this.CreateOrderItem(stockItem);
            this.AddingOrderItems(orderItem);
            this.BindDlOrderItems();
        }
        #endregion
    }
}